#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "Terminal.hpp"

using namespace std;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip, serverport\n" << std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
};

void* recv_data(void* args)
{
    OpenTerminal();
    ThreadData* td = static_cast<ThreadData*>(args);
    char buffer[1024];
    while(true)
    {
        // 1.数据 2.接收方的地址 3.地址长度
        struct sockaddr_in tmp;
        socklen_t length = sizeof(tmp);
        ssize_t s = recvfrom(td->sockfd, buffer, 1023, 0, (struct sockaddr *)&tmp, &length);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << buffer << endl;
        }`
    }
}

void* send_data(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    string message;
    while(true)
    {
        // 1.数据 2.接收方的地址 3.地址长度
        socklen_t len = sizeof(td->server);
        cout << "Please Enter@ ";
        getline(cin, message);
        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(td->server), len);
    }
}

// 多线程
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    u_int16_t serverport = stoi(argv[2]);

    struct ThreadData td;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());
    

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }

    // client需要bind吗？要！只不过不需要用户显示的bind！一般由操作系统随机选择
    // 一个端口号只能被一个进程bind，对server是如此，对client也是如此！
    // 其实client的port是多少，其实不重要，只要保证主机上的唯一性就可以！
    // 系统什么时候给我bind呢？首次发送数据的时候

    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recv_data, &td);
    pthread_create(&sender, nullptr, send_data, &td);

    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);

    close(td.sockfd);
    return 0;
}
